package com.zim.aliot.async;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.zim.aliot.util.RedisLockUtils;
import com.zim.analysis.po.PhotoPO;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class AsyncImage {
	 
	 @Autowired
	 private StringRedisTemplate stringRedisTemplate;
	 
	 @Autowired
	 private NotifyCommand notifyCommand;
	 
	 @Autowired
	 private RedisLockUtils redisLockUtils;
	 
	 @Async
	 public void image(String vin,String deviceName) {
		 long time = System.currentTimeMillis()+120000;
	     if(!redisLockUtils.lock(vin+"_lock", String.valueOf(time))) {
	    	 log.info("已经被锁");
	         return;
	     }
	     
	     Timer timer = new Timer();
	     TimerTask  task = new TimerTask (){
	    	 
			@Override
			public void run() {
				String imageHashKey = deviceName+"_img";
				HashOperations<String, String, String> imageHash = stringRedisTemplate.opsForHash();
		        Map<String, String> redisImage = imageHash.entries(imageHashKey);
		        StringBuffer image = new StringBuffer();
		        for (int i = 0; i < Integer.parseInt(redisImage.get("size")); i++) {
		        	image.append(redisImage.get(String.valueOf(i))==null?"":redisImage.get(String.valueOf(i)));
				}
		        
		        PhotoPO photoPO = new PhotoPO();
		        photoPO.setLongitude(Double.valueOf(redisImage.get("longitude")));
		        photoPO.setLatitude(Double.valueOf(redisImage.get("latitude")));
		        
		        notifyCommand.saveImage(vin, image.toString(), photoPO);
		        
		        stringRedisTemplate.delete(imageHashKey);
		        
		        redisLockUtils.unlock(vin+"_lock", String.valueOf(time));

			}
	    	 
	     };
	     
	     timer.schedule (task, 120000L);
	     
	 }
	 
}
